package com.kun.video.ui.window;

import com.kun.video.context.ContextService;
import com.kun.video.controller.Vlcj;
import com.kun.video.domain.VideoDataStaticContext;
import com.kun.video.thread.ComThreadPool;
import com.kun.video.ui.KunComponent;
import com.kun.video.ui.control.KunTextArea;
import com.kun.video.ui.dialog.message.PopupMessage;
import com.kun.video.ui.pane.KunImageViewBox;
import com.kun.video.ui.pane.VideoControlBox;
import com.kun.video.ui.pane.VideoToolBox;
import com.kun.video.util.ComUtil;
import com.kun.video.util.FFmpegParser;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.image.PixelBuffer;
import javafx.scene.image.PixelFormat;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.co.caprica.vlcj.factory.MediaPlayerFactory;
import uk.co.caprica.vlcj.player.base.MediaPlayer;
import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer;
import uk.co.caprica.vlcj.player.embedded.videosurface.CallbackVideoSurface;
import uk.co.caprica.vlcj.player.embedded.videosurface.VideoSurfaceAdapters;
import uk.co.caprica.vlcj.player.embedded.videosurface.callback.BufferFormat;
import uk.co.caprica.vlcj.player.embedded.videosurface.callback.BufferFormatCallback;
import uk.co.caprica.vlcj.player.embedded.videosurface.callback.RenderCallback;
import uk.co.caprica.vlcj.player.embedded.videosurface.callback.format.RV32BufferFormat;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.ByteBuffer;

/**
 * JavaFX组件，用于通过vlcj库实现视频播放
 * 注意：需要本地安装VLC 3.0+并配置环境变量
 * <p>
 * 实现原理：
 * 1. 使用vlcj的EmbeddedMediaPlayer进行媒体解码
 * 2. 通过CallbackVideoSurface将视频帧回调到JavaFX的ImageView
 * 3. 使用PixelBuffer实现直接内存映射，避免图像数据拷贝
 *
 * @author gzc
 * @since 2025/3/9
 **/
public class VideoView extends StackPane implements KunComponent {
    private static final Logger log = LoggerFactory.getLogger(VideoView.class);
    private static final String CSS_CLASS = "video-view";
    /**
     * 视频渲染容器
     */
    private MediaPlayerFactory mediaPlayerFactory;
    private EmbeddedMediaPlayer embeddedMediaPlayer;
    public final SimpleObjectProperty<File> currVideoFileProperty = new SimpleObjectProperty<>();
    private ComThreadPool comThreadPool;
    /**
     * 可写图像对象
     */
    private WritableImage videoImage;
    private ObjectProperty<WritableImage> videoImageProperty = new SimpleObjectProperty<>();
    private KunTextArea textArea;
    /**
     * 像素缓冲区
     */
    private PixelBuffer<ByteBuffer> videoPixelBuffer;
    /**
     * 视频解析参数
     */
    private FFmpegParser fFmpegParser;
    private final KunImageViewBox kunImageViewBox = new KunImageViewBox();
    private final VideoControlBox videoControlBox = new VideoControlBox();
    private final VideoToolBox videoToolBox = new VideoToolBox();
    /**
     * UI控件
     */
//    private final KunButton playPauseButton = new KunButton("▶", "开始播放");
//    private final KunButton playStopButton = new KunButton("⏹", "停止播放");
//    private final KunSlider playProgressSlider = new KunSlider();
//    private final KunSlider volumeSlider = new KunSlider(0, 100, 100);
//    private final Label timeLabel = new Label("00:00 / 00:00");
//    private final Label speedLabel = new Label("1.0x");
//    private final KunSlider speedSlider = new KunSlider(0.5, 2.0, 1.0);
    private final HBox playerBox = new HBox(10);
//    private final HBox controlBox = new HBox(5);
//    private final HBox buttonBox = new HBox(5);

    /**
     * 线程池用于刷新播放进度条
     */
//    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
//        Thread t = new Thread(r);
//        t.setDaemon(true);
//        t.setUncaughtExceptionHandler((thread, ex) ->
//                log.error("定时任务异常 -> ", ex)
//        );
//        return t;
//    });
    public VideoView() {
        initialize();
    }

    @Override
    public Parent getNode() {
        return this;
    }

    @Override
    public String getStyleName() {
        return CSS_CLASS;
    }

    @Override
    public void initStyleClass() {
        KunComponent.super.initStyleClass();
        kunImageViewBox.getStyleClass().add("player-box");
        videoControlBox.getStyleClass().add("control-box");
        videoToolBox.getStyleClass().add("button-box");
    }

    @Override
    public void initLayout() {
        // 初始化VLCJ播放器工厂
//        mediaPlayerFactory = new MediaPlayerFactory();
//        embeddedMediaPlayer = mediaPlayerFactory.mediaPlayers().newEmbeddedMediaPlayer();
//        // 配置视频渲染表面
//        embeddedMediaPlayer.videoSurface().set(new CustomerCallbackVideoSurface());
        VBox videoContainer = new VBox();
//        controlBox.setPadding(new Insets(5));
//        controlBox.getChildren().addAll(
//                playPauseButton,
//                playStopButton,
//                playProgressSlider,
//                timeLabel,
//                new Label("速率:"),
//                speedSlider,
//                speedLabel,
//                new Label("🔊"),
//                volumeSlider
//        );
        // 初始化按钮容器
        initButtonBox();
        playerBox.getChildren().add(kunImageViewBox);
        // 更新布局结构
//        videoContainer.getChildren().addAll(playerBox, controlBox, buttonBox);
        videoContainer.getChildren().addAll(playerBox, videoControlBox, videoToolBox);
        this.getChildren().add(videoContainer);

    }

    @Override
    public void initStyle() {
        // 时间标签样式
        playerBox.setAlignment(Pos.CENTER);
//        HBox.setHgrow(playProgressSlider, Priority.ALWAYS);
//        speedSlider.setShowTickLabels(true);
//        speedSlider.setSnapToTicks(true);
//        volumeSlider.setShowTickLabels(true);
    }

    @Override
    public void initDimensions() {
//        // 进度条配置
//        playProgressSlider.setMinWidth(300);
//        playProgressSlider.setMaxWidth(Double.MAX_VALUE);
//        // 速率滑块配置
//        speedSlider.setMajorTickUnit(0.5);
//        // 音量条配置
//        volumeSlider.setPrefWidth(100);
        // 进度条配置
        videoControlBox.playProgressSlider.setMinWidth(300);
        videoControlBox.playProgressSlider.setMaxWidth(Double.MAX_VALUE);
        // 速率滑块配置
        videoControlBox.speedSlider.setMajorTickUnit(0.5);
        // 音量条配置
        videoControlBox.volumeSlider.setPrefWidth(100);
    }

    @Override
    public void reactiveDimensions(double width, double height) {
        videoControlBox.setPrefSize(width, 50);
        videoControlBox.setMaxSize(width, 50);
//        buttonBox.setPrefSize(width, 50);
//        buttonBox.setMaxSize(width, 50);
        videoToolBox.setPrefSize(width, 50);
        videoToolBox.setMaxSize(width, 50);
        playerBox.setPrefSize(width, height - videoControlBox.getPrefHeight() - videoToolBox.getPrefHeight());
        playerBox.setMaxSize(width, height - videoControlBox.getPrefHeight() - videoToolBox.getPrefHeight());
        kunImageViewBox.setPrefSize(playerBox.getPrefWidth() - 50, playerBox.getPrefHeight() - 50);
        kunImageViewBox.setMinSize(playerBox.getPrefWidth() - 50, playerBox.getPrefHeight() - 50);
        kunImageViewBox.setMaxSize(playerBox.getPrefWidth() - 50, playerBox.getPrefHeight() - 50);
    }

//    /**
//     * 播放/暂停按钮
//     */
//    private final EventHandler<MouseEvent> playPauseEventHandler = event -> togglePlayPause();
//    /**
//     * 停止按钮
//     */
//    private final EventHandler<MouseEvent> playStopChangeListener = event -> stopMedia();
//    /**
//     * 播放进度条拖拽事件
//     */
//    private final EventHandler<? super MouseEvent> playProgressEventHandler = event -> seekMedia(null);
//    private final EventHandler<? super KeyEvent> keyEventEventHandler = event -> {
//        if (KeyCode.LEFT == event.getCode()) {
//            seekMedia(-15000);
//        } else if (KeyCode.RIGHT == event.getCode()) {
//            seekMedia(15000);
//        }
//    };
    /**
     * 音量调节
     */
    private final ChangeListener<Number> volumeChangeListener = (obs, ov, nv) -> embeddedMediaPlayer.audio().setVolume(nv.intValue());
//    /**
//     * 速率调节
//     */
//    private final ChangeListener<Number> speedChangeListener = (obs, ov, nv) -> updatePlaybackSpeed();
//    /**
//     * 添加媒体状态监听器
//     */
//    private final MediaPlayerEventAdapter mediaPlayerEventAdapter = new MediaPlayerEventAdapter() {
//        @Override
//        public void mediaChanged(MediaPlayer mediaPlayer, MediaRef media) {
//            ComUtil.uiThreadRun(() -> initMediaInfo());
//        }
//
//        @Override
//        public void opening(MediaPlayer mediaPlayer) {
//            ComUtil.uiThreadRun(() -> timeLabel.setText("加载中..."));
//        }
//    };

    @Override
    public void initListeners() {
//        ComponentUtil.weakActionEventHandler(playPauseButton, playPauseEventHandler);
//        ComponentUtil.weakActionEventHandler(playStopButton, playStopChangeListener);
//        ComponentUtil.weakActionEventHandler(playProgressSlider, MouseEvent.MOUSE_RELEASED, playProgressEventHandler);
//        ComponentUtil.weakActionEventHandler(playProgressSlider, KeyEvent.KEY_PRESSED, keyEventEventHandler);
//        ComponentUtil.weakChangeListener(speedSlider.valueProperty(), speedChangeListener);
//        ComponentUtil.weakChangeListener(volumeSlider.valueProperty(), volumeChangeListener);
//        embeddedMediaPlayer.events().addMediaPlayerEventListener(mediaPlayerEventAdapter);
        // 定时更新进度
//        scheduler.scheduleAtFixedRate(this::updateProgress, 0, 1, TimeUnit.SECONDS);
        videoImageProperty.addListener((observableValue, ov, nv) -> {
            videoToolBox.dataPassing(nv);
        });
    }

    @Override
    public void dispose() {
//        scheduler.shutdown();
        kunImageViewBox.dispose();
//        ComponentUtil.removeWeakListener(playPauseButton, playPauseEventHandler);
//        ComponentUtil.removeWeakListener(playStopButton, playStopChangeListener);
//        ComponentUtil.removeWeakListener(playProgressSlider, MouseEvent.MOUSE_RELEASED, playProgressEventHandler);
//        ComponentUtil.removeWeakListener(playProgressSlider, KeyEvent.KEY_PRESSED, keyEventEventHandler);
//        ComponentUtil.removeWeakListener(volumeSlider.valueProperty(), volumeChangeListener);
//        ComponentUtil.removeWeakListener(speedSlider.valueProperty(), speedChangeListener);
//        embeddedMediaPlayer.events().removeMediaPlayerEventListener(mediaPlayerEventAdapter);
//        if (embeddedMediaPlayer != null) {
//            embeddedMediaPlayer.release();
//        }
//        if (mediaPlayerFactory != null) {
//            mediaPlayerFactory.release();
//        }
//        playProgressSlider.dispose();
//        volumeSlider.dispose();
//        speedSlider.dispose();
        vlcj.dispose();
    }

    Vlcj vlcj;

    @Override
    public void initData() {
        comThreadPool = ContextService.getBean(ComThreadPool.class);
        this.kunImageViewBox.setSelectorConsumer((arr) -> {
            textArea.appendText(String.format("水印位置: x=%.1f, y=%.1f, 宽=%.1f, 高=%.1f\n",
                    arr[0], arr[1], arr[2], arr[3]));
        });
        videoToolBox.dataPassing(videoImageProperty);
        vlcj = new Vlcj();
        vlcj.setLoadCallback((parser) -> ComUtil.uiThreadRun(() -> {
            if (parser != null) {
                kunImageViewBox.updateSourceSize(parser.getWidth(), parser.getHeight());
                videoControlBox.playProgressSlider.setMin(0);
                videoControlBox.playProgressSlider.setMax(parser.getDurationMillis());
            }
        }));
        vlcj.setPlayCallback(() -> ComUtil.uiThreadRun(() -> {
            videoControlBox.playPauseButton.setText("⏸");
            new PopupMessage().success("开始播放", 1000);

        }));
        vlcj.setStopCallback(() -> ComUtil.uiThreadRun(() -> {
            videoControlBox.playPauseButton.setText("▶");
            new PopupMessage().success("暂停播放", 1000);
        }));
        vlcj.setSeekCallback(() -> ComUtil.uiThreadRun(() -> {
        }));
        vlcj.setRenderCallback((time) -> ComUtil.uiThreadRun(() -> {
            System.out.println("当前进度 -> " + time + " , 总时长 -> " + videoControlBox.playProgressSlider.getMax());
            long value = BigDecimal.valueOf(time).divide(BigDecimal.valueOf(1000), 2, RoundingMode.DOWN).longValue();
            long value1 = BigDecimal.valueOf(videoControlBox.playProgressSlider.getMax()).divide(BigDecimal.valueOf(1000), 2, RoundingMode.DOWN).longValue();
            System.out.println(value);
            videoControlBox.timeLabel.setText(formatTime(time) + " / " + formatTime((long) videoControlBox.playProgressSlider.getMax()));
            videoControlBox.playProgressSlider.setValue(time);
            if (value == value1) {
                videoControlBox.timeLabel.setText("00:00:00 / " + formatTime((long) videoControlBox.playProgressSlider.getMax()));
                videoControlBox.playPauseButton.setText("▶");
                videoControlBox.playProgressSlider.setValue(0);
                kunImageViewBox.setImage(null);
            }
        }));
        vlcj.setResetCallback((parser) -> ComUtil.uiThreadRun(() -> {
            videoControlBox.playPauseButton.setText("▶");
            videoControlBox.playProgressSlider.setValue(0);
        }));
        vlcj.imageProperty.addListener((observableValue, writableImage, t1) -> {
            videoImageProperty.setValue(t1);
            kunImageViewBox.setImage(t1);
        });
        videoControlBox.playPauseButton.action(() -> {
            if (vlcj.isPlaying()) {
                vlcj.stopMedia();
            } else {
                vlcj.playMedia();
            }
        });
        videoControlBox.playResetButton.action(() -> {
            vlcj.resetMedia();
            new PopupMessage().success("重新播放", 1000);
        });
        // 绑定
        VideoDataStaticContext.SELECT_FILE.addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                vlcj.loadMedia(newValue.getAbsolutePath());
            }
        });
    }

    public KunImageViewBox getKunImageViewBox() {
        return this.kunImageViewBox;
    }


//    /**
//     * 设置媒体源并开始播放
//     *
//     * @param videoPath 媒体文件路径（支持本地路径/网络流）
//     * @throws IllegalArgumentException 当路径无效时抛出异常
//     */
//    public void setMedia(String videoPath) {
//        vlcj.loadMedia(videoPath);
//        if (true) {
//            return;
//        }
//        // 停止当前播放
//        stopMedia();
//        if (StrUtil.isBlank(videoPath)) {
//            throw new BizException("媒体路径不能为空");
//        }
//        currVideoFileProperty.set(new File(videoPath));
//        // 解析视频
//        CommandExecutor.CommandResult result = CommandExecutor.executeCommand("ffmpeg", "-i", videoPath);
//        this.fFmpegParser = new FFmpegParser(result.getOutputStr());
//        ComUtil.uiThreadRun(() -> {
//            textArea.appendText(result.getOutputStr());
//
//        });
//        // 配置播放参数
//        String[] options = {
//                ":rtsp-tcp",                // 强制RTSP使用TCP传输
//                ":avcodec-hw=any",          // 启用硬件解码
//                ":network-caching=300",     // 网络缓存300ms
//                ":file-caching=1000",       // 文件缓存1s
//                ":live-caching=300"        // 直播流缓存
//        };
//
//        // 异步加载播放器
//        comThreadPool.runAsync(() -> {
//            try {
//                if (!FileUtil.exist(videoPath)) {
//                    throw new BizException("视频不存在");
//                }
//                embeddedMediaPlayer.media().prepare(videoPath, options);
//                embeddedMediaPlayer.controls().play();
//                new PopupMessage().success("播放视频" + videoPath, 1000);
//            } catch (Exception e) {
//                log.error("媒体播放失败: " + e.getMessage(), e);
//                new PopupMessage().error("媒体播放失败: " + e.getMessage(), 3000);
//                return;
//            }
//            ComUtil.uiThreadRun(() -> {
//                playPauseButton.setText("⏸");
//                kunImageViewBox.updateSourceSize(this.fFmpegParser.getWidth(), this.fFmpegParser.getHeight());
//
//            });
//        });
//    }

    private void initButtonBox() {
//        KunButton button1 = new KunButton("打开视频", "打开本地视频目录");
//        button1.action(() -> ComUtil.uiThreadRun(() -> {
//            File file = ChooserUtil.showFile(ChooserUtil.FileFormat.VIDEO);
//            if (file != null) {
//                setMedia(file.getAbsolutePath());
//            }
//        }));
//        KunButton button2 = new KunButton("截图", "视频当前帧截图保存到本地磁盘");
//        button2.action(this::snapshot);
//        buttonBox.getChildren().addAll(button2);
    }

//    private void updatePlaybackSpeed() {
//        double speed = speedSlider.getValue();
//        embeddedMediaPlayer.controls().setRate((float) speed);
//        speedLabel.setText(String.format("%.1fx", speed));
//    }

    /**
     * 初始化媒体元数据
     */
//    private void initMediaInfo() {
//        try {
//            MediaApi media = embeddedMediaPlayer.media();
//            if (media == null || media.info() == null) {
//                return;
//            }
//            // 触发解析
//            embeddedMediaPlayer.media().parsing().parse();
//            AbstractApplication.getAppStage().setTitle(currVideoFileProperty.get().getAbsolutePath());
//            // 在加载媒体后，显式触发解析
//            // 获取视频轨道信息
//            if (fFmpegParser != null) {
//                String resolution = StrUtil.format("{} x {}", fFmpegParser.getWidth(), fFmpegParser.getHeight());
//                String title = currVideoFileProperty.get().getAbsolutePath() +
//                        " 分辨率: " + resolution +
//                        " 帧率: " + fFmpegParser.getFps() +
//                        " 时长: " + fFmpegParser.getDuration();
//                AbstractApplication.getAppStage().setTitle(title);
//            }
//        } catch (Exception e) {
//            log.error("初始化媒体信息失败", e);
//        }
//    }

    /**
     * 媒体控制方法
     */
//    private void togglePlayPause() {
//        if (embeddedMediaPlayer.status().isPlaying()) {
//            embeddedMediaPlayer.controls().pause();
//            new PopupMessage().success("暂停播放", 1000);
//            ComUtil.uiThreadRun(() -> playPauseButton.setText("▶"));
//        } else {
//            embeddedMediaPlayer.controls().play();
//            new PopupMessage().success("开始播放", 1000);
//            ComUtil.uiThreadRun(() -> playPauseButton.setText("⏸"));
//        }
//    }

//    private void stopMedia() {
//        // 清空页面
//        kunImageViewBox.setImage(null);
//        embeddedMediaPlayer.controls().pause();
//        embeddedMediaPlayer.controls().stop();
//        ComUtil.uiThreadRun(() -> {
//            playPauseButton.setText("▶");
//            playProgressSlider.setValue(0);
//        });
//    }

//    private void seekMedia(Integer increment) {
//        float seekPosition;
//        if (increment == null) {
//            seekPosition = BigDecimal.valueOf(playProgressSlider.getValue())
//                    .divide(BigDecimal.valueOf(playProgressSlider.getMax()), 10, RoundingMode.HALF_UP).floatValue();
//        } else {
//            seekPosition = BigDecimal.valueOf(playProgressSlider.getValue() + increment)
//                    .divide(BigDecimal.valueOf(playProgressSlider.getMax()), 10, RoundingMode.HALF_UP).floatValue();
//        }
//        embeddedMediaPlayer.controls().setPosition(seekPosition);
//    }

//    private void updateProgress() {
//        ComUtil.uiThreadRun(() -> {
//            try {
//                // 空值保护
//                if (embeddedMediaPlayer == null ||
//                        embeddedMediaPlayer.media() == null ||
//                        embeddedMediaPlayer.media().info() == null) {
//                    // 媒体未准备好时直接返回
//                    return;
//                }
//                // 获取媒体总时长
//                long total = embeddedMediaPlayer.media().info().duration();
//                // 无效时长处理
//                if (total <= 0) {
//                    return;
//                }
//                // 获取当前播放时间
//                long current = embeddedMediaPlayer.status().time();
//                // 防止进度条抖动
//                if (Math.abs(playProgressSlider.getValue() - current) > 1000) {
//                    playProgressSlider.setValue(current);
//                }
//                // 更新UI组件
//                playProgressSlider.setMax(total);
//                playProgressSlider.setValue(current);
//                timeLabel.setText(formatTime(current) + " / " + formatTime(total));
//            } catch (Exception e) {
//                log.error("更新视频进度条失败: " + e.getMessage());
//            }
//        });
//    }

    /**
     * 截图文件输出目录
     */
//    private File snapshotOutputDir = new File("F:\\");
//    private void setSnapshotOutputDir(File file) {
//        this.snapshotOutputDir = file;
//    }
//    private CompletableFuture<Void> snapshot() {
//        CompletableFuture<Void> future = new CompletableFuture<>();
//        if (videoImage == null || snapshotOutputDir == null) {
//            return future;
//        }
//        String outputFileName = UUID.fastUUID().toString(true) + ".png";
//        String outputFilePath = this.snapshotOutputDir.getAbsolutePath() + File.separator + outputFileName;
//        // 保存截图到本地磁盘
//        return CompletableFuture.runAsync(() -> ImageUtil.savePng(videoImage, outputFilePath));
//    }
    private String formatTime(long milliseconds) {
        long seconds = milliseconds / 1000;
        return String.format("%02d:%02d:%02d", seconds / 60 / 60, seconds / 60, seconds % 60);
    }

    public void setTextArea(KunTextArea textArea) {
        this.textArea = textArea;
    }


    /**
     * 视频表面适配器，桥接VLCJ与JavaFX
     */
    private class CustomerCallbackVideoSurface extends CallbackVideoSurface {
        CustomerCallbackVideoSurface() {
            super(new CustomerBufferFormatCallback(),
                    new CustomerRenderCallback(),
                    true,
                    VideoSurfaceAdapters.getVideoSurfaceAdapter());
        }
    }

    /**
     * 缓冲区格式回调，处理视频尺寸变化
     */
    private class CustomerBufferFormatCallback implements BufferFormatCallback {
        private int sourceWidth;
        private int sourceHeight;

        @Override
        public BufferFormat getBufferFormat(int sourceWidth, int sourceHeight) {
            this.sourceWidth = sourceWidth;
            this.sourceHeight = sourceHeight;
            return new RV32BufferFormat(sourceWidth, sourceHeight);
        }

        @Override
        public void allocatedBuffers(ByteBuffer[] buffers) {
            // 验证缓冲区大小：width * height * 4 bytes（32位色深）
            assert buffers[0].capacity() == sourceWidth * sourceHeight * 4;
            // 创建JavaFX像素缓冲区
            PixelFormat<ByteBuffer> pixelFormat = PixelFormat.getByteBgraPreInstance();
            videoPixelBuffer = new PixelBuffer<>(sourceWidth, sourceHeight, buffers[0], pixelFormat);
            // 更新图像视图
            ComUtil.uiThreadRun(() -> {
                videoImage = new WritableImage(videoPixelBuffer);
                videoImageProperty.setValue(videoImage);
                kunImageViewBox.setImage(videoImage);
            });
        }
    }

    /**
     * 渲染回调，处理帧刷新
     */
    private class CustomerRenderCallback implements RenderCallback {
        @Override
        public void display(MediaPlayer mediaPlayer, ByteBuffer[] nativeBuffers, BufferFormat bufferFormat) {
            // 在JavaFX线程更新像素缓冲区
            ComUtil.uiThreadRun(() -> {
                if (videoPixelBuffer != null) {
                    // 触发缓冲区更新事件
                    videoPixelBuffer.updateBuffer(pb -> null);
                }
            });
        }
    }
}